<template>
  <lay-container fluid="true" style="padding: 10px">
    <lay-row :space="10">
      <lay-col :md="24">
        <lay-card shadow="hover">
          <lay-table :page="page" :columns="columns" :dataSource="dataSource" :default-toolbar="defaultToolbar"
            v-model:selectedKeys="selectedKeys" @change="change" :size="tablesize" :default-expand-all="true">
            <template v-slot:toolbar>
              <lay-button type="primary" size="sm" @click="add" v-permission="PerKey.UserDept_AddOrEditView">新增
              </lay-button>
            </template>
            <template v-slot:name="{ data }">
              {{data.deptName}}
            </template>
            <template v-slot:res="{ data }">
              <lay-button type="primary" size="sm" @click="contentCateRes(data.id)"
                v-permission="PerKey.UserDept_AddOrEditView">网站栏目
              </lay-button>
            </template>
            <template v-slot:operator="{ data }">
              <lay-button-group>
                <lay-button type="primary" size="sm" @click="edit(data.id)"
                  v-permission="PerKey.UserDept_AddOrEditView">编辑</lay-button>
                <lay-button type="danger" size="sm" @click="del(data)" v-permission="PerKey.UserDept_Delete">删除
                </lay-button>
              </lay-button-group>
            </template>
          </lay-table>
        </lay-card>
      </lay-col>
    </lay-row>

    <lay-layer :title="addoredittip" v-model="modelVisible" resize="true" :area="['800px','450px']"
      :offset="['40%','50%']">

      <lay-card style="padding:10px;">
        <lay-row space="10">
          <lay-form :model="form">
            <lay-col :md="24">
              <lay-form-item label="上级部门" prop="pid" required>
                <lay-col md="8">
                  <lay-select v-model="form.pid">
                    <lay-select-option v-for="cate in pids" :value="cate.id" :label="cate.deptName"
                      :disabled="cate.id==form.id"></lay-select-option>
                  </lay-select>
                </lay-col>
                <lay-col md="8" class="tip">不能选择自己作为上级部门</lay-col>
              </lay-form-item>

              <lay-form-item label="部门名称" prop="deptName" required required-error-message="部门名称不能空">
                <lay-col md="8">
                  <lay-input v-model="form.deptName"></lay-input>
                </lay-col>
              </lay-form-item>

              <lay-form-item label="排序" prop="orderNum">
                <lay-col md="8">
                  <lay-input v-model="form.orderNum"></lay-input>
                </lay-col>
                <lay-col md="8" class="tip">只为数字如：2</lay-col>
              </lay-form-item>
              <lay-form-item label="描述" prop="remark">
                <lay-col md="14">
                  <lay-textarea placeholder="请输入描述" v-model="form.remark">
                  </lay-textarea>
                </lay-col>
              </lay-form-item>
              <lay-form-item>
                <lay-button @click="submitClick" type="primary" v-permission="PerKey.UserDept_AddOrEdit">
                  {{addoredittip}}
                </lay-button>
              </lay-form-item>

            </lay-col>
          </lay-form>
        </lay-row>
      </lay-card>
    </lay-layer>


    <lay-layer :title="addoredittipCate" v-model="modelVisibleCate" resize="true" :area="['800px','450px']"
      :offset="['40%','50%']">
      <lay-card style="padding:10px;">
        <lay-row space="10">
          <lay-form :model="formCate">
            <lay-col :md="24">
              <lay-form-item label="部门名称" prop="deptNameCate">
                <lay-col md="6">
                  <lay-input v-model="formCate.deptName" :disabled="true"></lay-input>
                </lay-col>
              </lay-form-item>
              <lay-form-item label="网站栏目" prop="ContentCateRole">
                <lay-tree :data="treeData" v-model:checkedKeys="checkedKeys" :showCheckbox="true" collapse-transition>
                </lay-tree>
              </lay-form-item>
              <lay-form-item>
                <lay-button @click="submitClickCate" type="primary" v-permission="PerKey.UserDept_AddOrEdit">
                  {{addoredittipCate}}
                </lay-button>
              </lay-form-item>

            </lay-col>
          </lay-form>
        </lay-row>
      </lay-card>
    </lay-layer>
  </lay-container>
</template>

<script lang="ts" setup>
import { ref, toRefs, reactive } from "vue";
import { layer } from "@layui/layer-vue";
import { getList, delOne, getEdit, putEdit, postAdd, getEditContentRes, putEditContentRes } from "../../../api/module/user/userdept";
import { PerKey } from "../../../library/permissionConst"
import { useRouter } from "vue-router";
import { UserDept } from '../../../types/user'
const selectedKeys = ref(["1"]);
const defaultToolbar = ref(true);
const page = ref({ total: 0, limit: 10, current: 1, showRefresh: true, });
const tablesize = ref('md');
const router = useRouter();
const columns = [
  {
    title: "部门名称",
    width: "380px",
    key: "name", customSlot: "name",
  }, {
    title: "Id",
    width: "50px",
    key: "id"
  }, {
    title: "资源分配",
    width: "480px"
    , customSlot: "res"
  }, {
    title: "排序",
    width: "80px",
    key: "orderNum"
  }
  , {
    title: "备注",
    key: "remark"
  },
  {
    title: "操作",
    width: "200px",
    customSlot: "operator",
    key: "operator",
    align: "center",
  }
]
const dataSource = ref([])

const GetList = function () {
  getList().then((res) => {
    if (res.status == 1) {
      //console.log(res)
      dataSource.value = res.data

    }
  })
}

const change = function () {
  GetList();
};


const edit = function (id: number) {
  changeVisible(id)
}
const add = function () {
  changeVisible(0)
}

const del = function (data: any) {
  layer.confirm("确认删除ID: " + data.id + data.deptName + " 部门", {
    title: "警告", move: "true", shade: "false", shadeClose: "true",
    btn: [{
      text: '确认', callback: (layerId: number) => {
        delOne(data.id).then((res) => {
          if (res.status == 1) {            
            layer.msg(res.msg, { time: 1000, icon: 1 },()=>{
              GetList()
            });
          } else {
            layer.msg(res.msg);
          }
          layer.close(layerId);
        })
      }
    }, {
      text: '取消', callback: function (layerId: number) {
        layer.close(layerId);
      }
    }]
  })
}



//添加或者编辑
//
//
const pids = ref({ targetList: [] as any, })

const modelVisible = ref(false)
const data = reactive({
  form: <UserDept><unknown>[]
})


const { form } = toRefs(data)

let addoredittip = ref();

const changeVisible = function (id: number) {
  modelVisible.value = !modelVisible.value
  if (id == 0) {
    addoredittip.value = "新增部门";
    getEdit(id).then((res) => {
      pids.value = res.deptList
      form.value = {
        id: 0,
        pid: 0,
        deptName: "",
        orderNum: "",
        remark: "",
      }
    })
    return
  } else {
    addoredittip.value = "编辑部门";
    getEdit(id).then((res) => {
      pids.value = res.deptList
      if (res.status == 1) {
        let data = res.data
        form.value = data
      }
    })
    return
  }
}

const submitClick = function () {
  if (!form.value.deptName) {
    layer.msg("部门名称不能空")
    return
  }
  if (form.value.id == 0) {
    postAdd(form.value).then((res) => {
      done(res)
    });
  } else {
    putEdit(form.value).then((res) => {
      done(res)
    });
  }
};
const done = (res: any) => {

  if (res.status == 1) {
    layer.msg(res.msg, () => { });
    modelVisible.value = !modelVisible.value
    GetList()
  } else {
    layer.msg(res.msg, { icon: 2 });
    return false;
  }
}

//网站栏目资源分配
//
//

const contentCateRes = function (id: number) {
  changeVisibleCate(id)
}

const modelVisibleCate = ref(false)
const dataCate = reactive({
  formCate: {
    id: 0,
    contentCateRole: "",
    deptName: "",
  }
})

const { formCate } = toRefs(dataCate)

let addoredittipCate = ref();

const treeData = ref([])
const checkedKeys = ref([])

const changeVisibleCate = function (id: number) {
  modelVisibleCate.value = !modelVisibleCate.value
  getEditContentRes(id).then((res) => {
    addoredittipCate.value = "分配网站栏目资源";
    checkedKeys.value = [];
    if (res.status == 1) {
      treeData.value = res.allTree
      let data = res.data
      formCate.value = {
        id: data.id,
        deptName: data.deptName,
        contentCateRole: ""
      }
      let cate = JSON.parse(data.contentCateRole)
      if (cate != null) {
        var turnNum = function (cate: any) {
          return cate.map(Number);
        }
        checkedKeys.value = turnNum(cate)
      }
    }
  })
}

const submitClickCate = function () {
  formCate.value.contentCateRole = JSON.stringify(checkedKeys.value)
  putEditContentRes(formCate.value).then((res) => {
    if (res.status == 1) {
      layer.msg(res.msg, { time: 1000, icon: 1 }, () => {
        modelVisibleCate.value = !modelVisibleCate.value
        GetList()
      });
    } else {
      layer.msg(res.msg, { icon: 2 });
      return false;
    }
  });
}

GetList()


</script>

<style scoped>
.tip {
  color: gray;
  line-height: 38px;
  height: inherit;
  padding-left: 10px;
}
</style>